require 'sitebuilder/string'
require 'sitebuilder/actions'
require 'fileutils'
require 'oofile'

module SiteBuilder
  
  # I generate a target website directory from a source website directory
  # using mapping rules that determine what should be done for each file
  # of the source website directory.
  class SiteGenerator < OOFile::Traverser
    
    # I set up the source website directory and the destination website directory.
    def initialize(source, destination, default_action=CopyAction.new) 
      @swapout = source
      @replace = destination
      @actions = {}
      @actions.default = default_action
    end
    
    # internal callback used to handle a source directory
    def traverse_dir(dir_entry)
        converted_path = dir_entry.path.clone
        converted_path.substitute_prefix!(@swapout, @replace)
        FileUtils.mkdir_p(converted_path)
    end
    
    # internal callback used to handle a source file
    def traverse_file(file_entry)
      if !file_entry.path.index('.svn')
        converted_path = file_entry.dirname
        converted_path.substitute_prefix!(@swapout, @replace) #BUG? - no clone here?
        @actions[file_entry.extname].convert(file_entry, converted_path)
      end
    end

    def add_action(extension, action) 
      @actions[extension]=action
    end
    
    # Initiate site generation
    def generate
      OOFile::DirEntry.new(@swapout).traverse(self)
    end
  end

end
